package cn.net.yugu.doraemon.common.mybatis.typehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

/**
 * java.time.Instant 与 MySQL bigint(20) 类型转换器
 *
 * @author xiangzr
 * @version 2021/7/21 16:29:08
 */
@MappedJdbcTypes(JdbcType.BIGINT)
@MappedTypes(Instant.class)
@Slf4j
public class InstantTypeHandler extends BaseTypeHandler<Instant> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Instant parameter, JdbcType jdbcType) throws SQLException {
        ps.setLong(i, parameter.toEpochMilli());
    }

    @Override
    public Instant getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Long epochMilli = rs.getLong(columnName);
        return getInstant(epochMilli);
    }

    @Override
    public Instant getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Long epochMilli = rs.getLong(columnIndex);
        return getInstant(epochMilli);
    }

    @Override
    public Instant getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Long epochMilli = cs.getLong(columnIndex);
        return getInstant(epochMilli);
    }

    private static Instant getInstant(Long epochMilli) {
        if (epochMilli != null) {
            return Instant.ofEpochMilli(epochMilli);
        }
        return null;
    }
}
